<!-- src/views/ChatView.vue -->
<script setup>
import {onMounted, ref} from 'vue'
import {ElMessage} from 'element-plus'
import http from "@/request/Http.js";
import router from "@/router/index.js";

// 当前用户
const currentUserId = ref(null)
const currentUser = ref(null) // 新增：存储当前用户完整信息

// 好友列表
const friends = ref([])
const filteredFriends = ref([])
const searchUser = ref('')

// 当前聊天对象
const selectedUser = ref(null)
const messages = ref([])
const newMessage = ref('')

// ------------------- 加载好友列表 -------------------
const loadFriends = async () => {
  try {
    const res = await http.get('/message/friends/list')
    const friendIds = res.data

    console.log(friendIds)

    if (!Array.isArray(friendIds) || friendIds.length === 0) {
      ElMessage.info('暂无好友')
      return
    }

    // ✅ 过滤掉空值或非数字 ID
    const validIds = friendIds.filter(id => {
      return typeof id === 'number' && id > 0
    })

    if (validIds.length === 0) {
      ElMessage.info('暂无有效好友')
      return
    }

    const userListRes = await http.post('/message/listByIds', {ids: validIds})
    const userList = userListRes.data

    friends.value = userList || []
    filteredFriends.value = friends.value
  } catch (err) {
    console.error('加载好友失败:', err)
    ElMessage.error('加载好友失败')
  }
}

// ------------------- 搜索好友 -------------------
const filterFriends = () => {
  const keyword = searchUser.value.toLowerCase()
  filteredFriends.value = friends.value.filter(u =>
      u.username.toLowerCase().includes(keyword)
  )
}

// ------------------- 选择用户开始聊天 -------------------
const selectUser = async (user) => {
  selectedUser.value = user
  messages.value = []

  try {
    console.log('🔍 开始加载聊天记录，对方用户ID:', user.id)

    const response = await http.get('/message/getChatHistory', {
      params: {
        otherUserId: user.id
      }
    })

    console.log('✅ 后端返回数据:', response)

    // 修正：正确处理消息数据
    if (response && response.data) {
      const messageList = Array.isArray(response.data) ? response.data : []

      // 确保每条消息都有正确的 senderId
      messages.value = messageList.map(msg => {
        // 如果消息中没有 senderId，根据当前用户判断
        if (!msg.senderId) {
          // 这里需要根据你的后端数据结构调整
          // 假设消息中有 fromUserId 和 toUserId 字段
          if (msg.fromUserId === currentUserId.value) {
            msg.senderId = currentUserId.value
          } else {
            msg.senderId = user.id
          }
        }
        return msg
      })
    } else {
      messages.value = []
    }

    console.log('📊 最终消息列表:', messages.value)
  } catch (err) {
    console.error('❌ 加载聊天记录失败:', err)
    ElMessage.error('加载聊天记录失败: ' + (err.response?.data?.message || err.message))
  }
}

// ------------------- 发送消息 -------------------
const sendMessage = async () => {
  const content = newMessage.value.trim();
  if (!content || !selectedUser.value) return;

  const message = {
    receiverId: selectedUser.value.id,
    content: content,
    msgType: 'text'
  };

  try {
    // 发送消息到服务器
    const response = await http.post('/message/sendMessage', message);

    // 修正：使用服务器返回的消息数据，而不是手动创建
    if (response && response.data) {
      const sentMessage = response.data;

      // 确保消息有正确的 senderId
      if (!sentMessage.senderId) {
        sentMessage.senderId = currentUserId.value;
      }

      messages.value.push(sentMessage);
    } else {
      // 如果后端没有返回消息数据，手动创建但确保 senderId 正确
      messages.value.push({
        ...message,
        senderId: currentUserId.value,
        createdAt: new Date().toISOString()
      });
    }

    newMessage.value = '';
  } catch (err) {
    ElMessage.error('发送失败');
  }
};

// ------------------- 上传并发送图片 -------------------
const handleImageUpload = async (event) => {
  const file = event.target.files[0]
  if (!file || !selectedUser.value) return

  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('图片不能超过 5MB')
    return
  }

  const formData = new FormData()
  formData.append('file', file)

  try {
    const res = await http.post('/message/upload/image', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })

    const imageUrl = res.data.data

    const message = {
      receiverId: selectedUser.value.id,
      content: imageUrl,
      msgType: 'image'
    }

    const response = await http.post('/message/sendMessage', message)

    // 修正：使用服务器返回的数据
    if (response && response.data) {
      const sentMessage = response.data;
      if (!sentMessage.senderId) {
        sentMessage.senderId = currentUserId.value;
      }
      messages.value.push(sentMessage);
    } else {
      messages.value.push({
        ...message,
        senderId: currentUserId.value,
        createdAt: new Date().toISOString()
      })
    }
  } catch (err) {
    ElMessage.error('图片发送失败')
  }

  event.target.value = ''
}

// ------------------- 格式化时间 -------------------
const formatTime = (timeString) => {
  if (!timeString) return ''
  const date = new Date(timeString)
  const now = new Date()

  if (date.toDateString() === now.toDateString()) {
    return date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  const yesterday = new Date(now)
  yesterday.setDate(yesterday.getDate() - 1)
  if (date.toDateString() === yesterday.toDateString()) {
    return '昨天 ' + date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  return date.toLocaleDateString('zh-CN') + ' ' +
      date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })
}

// ------------------- 页面加载 -------------------
onMounted(async () => {
  const token = sessionStorage.getItem('token')
  if (!token) {
    ElMessage.error('请先登录')
    return router.push('/login')
  }

  try {
    const response = await http.get('/message/user/info')

    console.log('✅ 用户信息响应:', response)

    const userInfo = response.data

    if (!userInfo || (!userInfo.userId && !userInfo.id)) {
      ElMessage.error('用户信息不完整')
      return router.push('/login')
    }

    // 修正：同时存储用户ID和完整用户信息
    currentUserId.value = userInfo.userId || userInfo.id
    currentUser.value = userInfo // 存储完整用户信息
    sessionStorage.setItem('user', JSON.stringify(userInfo))

    await loadFriends()
  } catch (err) {
    console.error('初始化失败:', err)
    ElMessage.error('用户信息获取失败，请重新登录')
    return router.push('/login')
  }
})

// 修正：获取发送者显示名称的函数
const getSenderDisplayName = (senderId) => {
  if (senderId === currentUserId.value) {
    return currentUser.value?.username || '我'
  } else if (selectedUser.value && senderId === selectedUser.value.id) {
    return selectedUser.value.username
  } else {
    // 如果是其他发送者，尝试从好友列表中查找
    const sender = friends.value.find(friend => friend.id === senderId)
    return sender?.username || '未知用户'
  }
}

// 修正：获取发送者头像的函数
const getSenderAvatar = (senderId) => {
  if (senderId === currentUserId.value) {
    return currentUser.value?.avatar
  } else if (selectedUser.value && senderId === selectedUser.value.id) {
    return selectedUser.value.avatar
  } else {
    const sender = friends.value.find(friend => friend.id === senderId)
    return sender?.avatar
  }
}
</script>

<template>
  <div class="chat-container">
    <!-- 左侧：用户列表 -->
    <div class="user-panel">
      <div class="search-box">
        <el-input
            v-model="searchUser"
            clearable
            placeholder="搜索用户"
            @input="filterFriends"
        >
          <template #prefix>
            <el-icon>
              <Search/>
            </el-icon>
          </template>
        </el-input>
      </div>

      <div class="user-list">
        <div
            v-for="user in filteredFriends"
            :key="user.id"
            :class="{ active: selectedUser?.id === user.id }"
            class="user-item"
            @click="selectUser(user)"
        >
          <div class="user-avatar">
            <img v-if="user.avatar" :src="user.avatar" alt="avatar"/>
            <div v-else class="default-avatar">{{ user.username?.charAt(0) }}</div>
          </div>
          <div class="user-info">
            <div class="username">{{ user.username }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧：聊天区域 -->
    <div class="chat-panel">
      <!-- 聊天标题 -->
      <div v-if="selectedUser" class="chat-header">
        <div class="chat-user-info">
          <div class="chat-user-avatar">
            <img v-if="selectedUser.avatar" :src="selectedUser.avatar" alt="avatar"/>
            <div v-else class="default-avatar">{{ selectedUser.username?.charAt(0) }}</div>
          </div>
          <span class="user-name">{{ selectedUser.username }}</span>
        </div>
      </div>

      <!-- 聊天内容 -->
      <div v-if="selectedUser" class="chat-messages">
        <div
            v-for="(msg, index) in messages"
            :key="index"
            :class="{
              'message-sent': msg.senderId === currentUserId.value,
              'message-received': msg.senderId !== currentUserId.value
            }"
            class="message-item"
        >
          <!-- 接收的消息（左侧显示） -->
          <div v-if="msg.senderId !== currentUserId.value" class="message-received-wrapper">
            <div class="message-avatar">
              <img v-if="getSenderAvatar(msg.senderId)" :src="getSenderAvatar(msg.senderId)" alt="avatar"/>
              <div v-else class="default-avatar small">{{ getSenderDisplayName(msg.senderId)?.charAt(0) }}</div>
            </div>
            <div class="message-content">
              <div class="message-sender">{{ getSenderDisplayName(msg.senderId) }}</div>
              <div class="message-bubble received">
                {{ msg.content }}
              </div>
              <div class="message-time">
                {{ formatTime(msg.createdAt) }}
              </div>
            </div>
          </div>

          <!-- 发送的消息（右侧显示） -->
          <div v-else class="message-sent-wrapper">
            <div class="message-content">
              <div class="message-sender">{{ getSenderDisplayName(msg.senderId) }}</div>
              <div class="message-bubble sent">
                {{ msg.content }}
              </div>
              <div class="message-time">
                {{ formatTime(msg.createdAt) }}
              </div>
            </div>
            <div class="message-avatar">
              <img v-if="getSenderAvatar(msg.senderId)" :src="getSenderAvatar(msg.senderId)" alt="avatar"/>
              <div v-else class="default-avatar small">{{ getSenderDisplayName(msg.senderId)?.charAt(0) }}</div>
            </div>
          </div>
        </div>
        <p v-if="messages.length === 0" class="no-messages">暂无消息记录</p>
      </div>

      <div v-else class="chat-placeholder">
        选择一个用户开始聊天
      </div>

      <!-- 输入框 -->
      <div v-if="selectedUser" class="chat-input">
        <el-input
            v-model="newMessage"
            clearable
            placeholder="输入消息..."
            @keyup.enter="sendMessage"
        >
          <template #suffix>
            <input
                type="file"
                ref="fileInput"
                @change="handleImageUpload"
                accept="image/*"
                style="display: none"
            />
            <el-button
                size="small"
                icon="Picture"
                @click="$refs.fileInput.click()"
                style="margin-right: 8px"
            />
            <el-button size="small" type="primary" @click="sendMessage">
              发送
            </el-button>
          </template>
        </el-input>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 样式保持不变 */
.chat-container {
  display: flex;
  height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  background: #f5f5f5;
}

.user-panel {
  width: 300px;
  border-right: 1px solid #ddd;
  display: flex;
  flex-direction: column;
  background: white;
}

.search-box {
  padding: 12px;
  border-bottom: 1px solid #eee;
}

.user-list {
  flex: 1;
  overflow-y: auto;
}

.user-item {
  padding: 12px 16px;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
  transition: background 0.2s;
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-item:hover {
  background-color: #f5f5f5;
}

.user-item.active {
  background-color: #e6f2ff;
  font-weight: bold;
  color: #1976d2;
}

.chat-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fafafa;
}

.chat-header {
  padding: 16px;
  background: #f9f9f9;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.chat-user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.chat-user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  overflow: hidden;
}

.chat-user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.message-item {
  display: flex;
}

.message-received-wrapper {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  max-width: 70%;
}

.message-sent-wrapper {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  max-width: 70%;
  margin-left: auto;
  flex-direction: row-reverse;
}

.message-avatar {
  flex-shrink: 0;
}

.message-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.message-sent-wrapper .message-content {
  align-items: flex-end;
}

.message-bubble {
  max-width: 100%;
  padding: 10px 14px;
  border-radius: 18px;
  font-size: 14px;
  line-height: 1.4;
  word-wrap: break-word;
}

.message-bubble.received {
  background: white;
  color: #333;
  border: 1px solid #e0e0e0;
  border-bottom-left-radius: 4px;
}

.message-bubble.sent {
  background: #409eff;
  color: white;
  border-bottom-right-radius: 4px;
}

.message-time {
  font-size: 12px;
  color: #999;
  padding: 0 4px;
}

.message-sender {
  font-size: 12px;
  color: #888;
  font-weight: 500;
  margin-bottom: 2px;
}

.no-messages {
  text-align: center;
  color: #999;
  font-style: italic;
  margin-top: 20px;
}

.chat-placeholder {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #999;
  font-size: 18px;
}

.chat-input {
  padding: 12px;
  background: white;
  border-top: 1px solid #eee;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}

.default-avatar.small {
  width: 32px;
  height: 32px;
  font-size: 12px;
}

.user-info {
  flex: 1;
}

.username {
  font-weight: 500;
}
</style>